package com.threegold.listviewsample.slice;

import com.threegold.listview.ListView;
import com.threegold.listviewsample.ResourceTable;
import com.threegold.listviewsample.provider.CommonListItemProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

import java.util.ArrayList;
import java.util.List;

public class BasicUsageAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_basic_usage);
        // 基本用法3个步骤：
        // 1、自定义适配器，继承自ListItemProvider实现子类
        // 2、添加数据。
        // 3、绑定适配器

        ListView listView = (ListView) findComponentById(ResourceTable.Id_listView);
        // 创建适配器
        CommonListItemProvider itemProvider = new CommonListItemProvider(this);
        // 设置数据集合
        itemProvider.setDataList(getDatas());
        // 绑定适配器，注意使用ListView必须使用ListItemProvider的子类适配器，否则强制报错
        listView.setItemProvider(itemProvider);
        // 设置Item单击事件
        listView.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(Component component, Object data, int position) {
                showToast("onItemClick " + position + ", " + data);
            }
        });

        // 设置Item长按事件
        listView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(Component component, Object data, int position) {
                showToast("onItemLongClick " + position + ", " + data);
            }
        });
    }

    private void showToast(String msg) {
        new ToastDialog(getContext()).setAlignment(LayoutAlignment.CENTER).setText(msg).show();
    }

    private List<String> getDatas() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            list.add("item" + i);
        }
        return list;
    }

}
